package cn.ciis.sys.account;

import cn.ciis.basic.base.BaseService;
import cn.ciis.basic.model.Account;
import cn.ciis.basic.model.Role;
import cn.ciis.basic.model.Session;
import cn.ciis.sys.login.LoginService;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;

import java.util.List;

/**
 * 账户管理
 *
 * @author 冉志林
 */
public class AccountAdminService extends BaseService {

    @Inject
    LoginService loginSrv;

    private Account dao = new Account().dao();
    private final String allAccountsCacheName = "allAccounts";
    private static final Session SESSION_DAO = new Session().dao();

    @Override
    public Model getDao() {
    return dao;
  }

    public List<Session> listSession(String accountId) {
        return SESSION_DAO.find(
                "SELECT * FROM `sys_session` GROUP BY accountId HAVING accountId in(" + accountId + ")");
    }

    /**
     * 注意要验证userName 是否存在
     */
    public Ret update(Account account) {
        String userName = account.getUserName().toLowerCase().trim();
        String sql = "select id from sys_account where lower(userName) = ? and id != ? limit 1";
        Integer id = Db.queryInt(sql, userName, account.getId());
        if (id != null) {
            return Ret.fail("msg", "邮箱已经存在，请输入别的邮箱");
        }

        // 暂时只允许修改 userName
        account.keep("id", "userName");
        account.update();
        return Ret.ok("msg", "账户更新成功");
    }

    /**
     * 锁定账号
     */
    public Ret lock(int loginAccountId, int lockedAccountId) {
        if (loginAccountId == lockedAccountId) {
            return Ret.fail("msg", "不能锁定自己的账号");
        }

        int n =
                Db.update(
                        "update sys_account set status = ? where id=?",
                        Account.STATUS_LOCK_ID,
                        lockedAccountId);

        // 锁定后，强制退出登录，避免继续搞破坏
        List<Session> sessionList =
                Session.DAO.find("select * from sys_session where accountId = ?", lockedAccountId);
        if (sessionList != null) {
            // 处理多客户端同时登录后的多 session 记录
            for (Session session : sessionList) {
                // 清除登录 cache，强制退出
                loginSrv.logout(session.getId());
            }
        }

        if (n > 0) {
            return Ret.ok("msg", "锁定成功");
        } else {
            return Ret.fail("msg", "锁定失败");
        }
    }

    /**
     * 解锁账号
     */
    public Ret unlock(int accountId) {
        // 如果账户未激活，则不能被解锁
        int n =
                Db.update(
                        "update sys_account set status = ? where status != ? and id = ?",
                        Account.STATUS_OK,
                        Account.STATUS_REG,
                        accountId);
        Db.update("delete from sys_session where accountId = ?", accountId);
        if (n > 0) {
            return Ret.ok("msg", "解锁成功");
        } else {
            return Ret.fail("msg", "解锁失败，可能是账户未激活，请查看账户详情");
        }
    }

    /**
     * 添加角色
     */
    public Ret addRole(int accountId, int roleId) {

        Record accountRole = new Record().set("accountId", accountId).set("roleId", roleId);
        Db.save("sys_account_role", accountRole);
        return Ret.ok("msg", "添加角色成功");
    }

    /**
     * 删除角色
     */
    public Ret deleteRole(int accountId, int roleId, int loginId) {
        if (accountId == 1 && roleId == 1) {
            return Ret.fail("msg", "超级管理员不能删除自己");
        }
        if (loginId == accountId) {
            return Ret.fail("msg", "最好不要删除自己的角色");
        }
        Db.delete("delete from sys_account_role where accountId=? and roleId=?", accountId, roleId);
        return Ret.ok("msg", "删除角色成功");
    }

    /**
     * 删除当前用户的所有角色
     */
    public Ret deleteRole(String accountId) {
        if (String.valueOf(1).equals(accountId)) {
            return Ret.fail("msg", "超级管理员不能删除自己");
        }
        Db.delete("delete from sys_account_role where accountId=?", accountId);
        return Ret.ok("msg", "删除角色成功");
    }

    /**
     * 标记出 account 拥有的角色 未来用 role left join account_role 来优化
     */
    public void markAssignedRoles(Account account, List<Role> roleList) {
        String sql = "select accountId from sys_account_role where accountId=? and roleId=? limit 1";
        for (Role role : roleList) {
            Integer accountId = Db.queryInt(sql, account.getId(), role.getId());
            if (accountId != null) {
                // 设置 assigned 用于界面输出 checked
                role.put("assigned", true);
            }
        }
    }

    /**
     * 登录账号是否重复（登录名、手机号、邮箱）
     */
    public boolean isNull(String key, String v, Integer id) {
        String sql = "select * from sys_account where " + key + "=? and id<>?";
        return dao.findFirst(sql, v, id) != null;
    }

    /**
     * 列表页获取创建人名字
     *
     * @return
     */
    public List<Account> getListAccount() {
        return dao.find("SELECT id,fullName FROM `sys_account` where status=1");
    }

}
